<?php

namespace app\api\controller\v1;

use app\BaseController;
// 引入jwt插件
use thans\jwt\facade\JWTAuth;

class Token extends BaseController
{
    public function read()
    { 
        //小程序端传来的用户登录凭证
        $code = $_GET['code'] ?? '';
        // dump($code);die;
        $appid = 'wx365ce10c10b427a1';
        $secret = '98ada6ea182b762ccd481a7892fece12';

        //发送请求的url
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $result = https_request($url); //发送HTTP请求，返回数据

        $json_obj = json_decode($result, true);

        $openid = $json_obj['openid'];  //从返回的数据中获取openid
        $session_key = $json_obj['session_key'];  //从返回的数据中获取session_key
        $str = $openid . $session_key;
        // dump($openid);

        //重新获取token将旧token拉进黑名单
        // JWTAuth::refresh();

        // 生成token
        $token = JWTAuth::builder(['token' => $str]);
        // dump($token);
        // die;
        file_put_contents('./token.txt', $token);

        return json(['code' => '200', 'msg' => '获取token成功', 'token' => $token,'openid' => $openid]);
    }
}
